package com.design.reactor.stretchIO._4_masterSlaveReactorMultiThread;

import com.design.reactor.stretchIO._4_masterSlaveReactorMultiThread.handler.Handler;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Set;

public class SubReactor implements Runnable {

    private Selector selector;
    /**SubReactor 所在线程是否已经启动 */
    private boolean isThreadStarted;

    public SubReactor() throws IOException {
        this.selector = Selector.open();
    }

    public SubReactor(Selector selector) {
        this.selector = selector;
    }

    @Override
    public void run() {
        while (!Thread.interrupted()) { // 在線程被中斷前持續運行
            try {
                selector.select(); // 若沒有事件就緒則不往下執行
                Set<SelectionKey> selectedKeys = selector.selectedKeys(); // 取得所有已就緒事件的key集合
                for (SelectionKey selectedKey : selectedKeys) {
                    dispatch(selectedKey); // 根據事件的key進行調度
                }
                selectedKeys.clear();
            } catch (IOException e) {
                e.getLocalizedMessage();
            }
        }
    }

    /*
     * name: dispatch(SelectionKey key) description: 調度方法，根據事件綁定的對象開新線程
     */
    private void dispatch(SelectionKey key) {
        Handler r = (Handler) (key.attachment()); // 根據事件之key綁定的對象開新線程
        if (r != null)
            r.processes();
    }

    public void setSelector(Selector selector) {
        this.selector = selector;
    }

    public Selector getSelector() {
        return this.selector;
    }

    public boolean isThreadStarted() {
        return isThreadStarted;
    }

    public void setThreadStarted(boolean threadStarted) {
        isThreadStarted = threadStarted;
    }
}
